<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php

class Trash extends CApiComponent
{
    public $fromIds;      public $trashList;
    public $_userNick;
    const LIST_TRASH = 0;
    const REVERT = 1;     const DELETE = 2;     const CLEAN = 3;     
    public function __construct ()
    {
        parent::init();
        $this->result = array();
        $this->result["state"] = false;
        $this->result["code"] = 0;
        $this->result["msg"] = "操作失败";
    }
    
    public function invoke ($action = 0)
    {
        switch ($action) {
            case Trash::LIST_TRASH:
                $this->handleListTrash();
                break;
            case Trash::REVERT:
                $this->handleRevert();
                break;
            case Trash::DELETE:
                $this->handleDelete();
                break;
            case Trash::CLEAN:
                $this->handleClean();
                break;
            default:
                break;
        }
    }
    
    
    private function handleListTrash ()
    {
        $fileHandle = new TrashList();
        $count = $fileHandle->trashCount($this->_userId);
        $this->trashList = $fileHandle->obtainTrashList($this->_userId, $this->limit, $this->offset);
    }
    
    
    private function handleRevert() {
                $device = new UserDevice();
        $device = $device->findByUserIdAndType($this->_userId, 1);
        $this->_deviceId = $device["id"];
        $user = User::model()->findByPk($this->_userId);
        $this->_userNick = $user["user_name"];
        $files = UserFile::model()->getFilesByIds($this->_userId, $this->fromIds, 1);
        foreach ($files as $file) {
            $path = $file["file_path"];
            $file["is_deleted"] = 0;
            $file["event_uuid"] = CUtils::random_string(46);
            $file->save();
                        $event = new UserEvent();
            if ($file["file_type"] == 0) {
                $version = FileVersion::model()->findByPk($file["version_id"]);
                                $this->handleFileMeta($path, $file["version_id"], $this->_userId, $this->_userNick, 3);
                $hash = $version["file_signature"];
                $context = array( "hash"  => $hash,
                          "rev"   => (int)$file["version_id"],
                          "bytes" => (int)$file["file_size"]);
                $event->CreateEvent($this->_userId, $this->_deviceId, 3, $path, serialize($context), $file["event_uuid"]);
                continue;
            }
            
                        $event->CreateEvent($this->_userId, $this->_deviceId, 0, $path, $path, $file["event_uuid"]);
                        $children = UserFile::model()->getFilesByPath($path, 1);
            foreach ($children as $child) {
                $child["is_deleted"] = 0;
                $child["event_uuid"] = CUtils::random_string(46);
                $child->save();
                $path = $childcontext = $child["file_path"];
                $event = new UserEvent();
                                 if ($child["file_type"] == 0) {
                     $version = FileVersion::model()->findByPk($child["version_id"]);
                                          $this->handleFileMeta($path, $child["version_id"], $this->_userId, $this->_userNick, 3);
                     $hash = $version["file_signature"];
                     $childcontext = array( "hash"  => $hash,
                              "rev"   => (int)$child["version_id"],
                              "bytes" => (int)$child["file_size"]);
                     $childcontext = serialize($childcontext);
                                          $event->CreateEvent($this->_userId, $this->_deviceId, 3, $path, $childcontext, $child["event_uuid"]);
                     continue;
                 }
                                  $event->CreateEvent($this->_userId, $this->_deviceId, 0, $path, $childcontext, $child["event_uuid"]);
            }
        }
        $this->handleResult(TRUE, 0, "操作成功");
    }
    
    
    private function handleDelete() {
        if ($this->fromIds == "-1") {
            throw new ApiException("参数错误");
        }
                $files = UserFile::model()->getFilesByIds($this->_userId, $this->fromIds, 1);
                FileStar::model()->deleteAllByFileIds($this->_userId, $this->fromIds);
        ShareFile::model()->deleteShareFile($this->fromIds);
        
                foreach ($files as $file) {
            if ($file["file_type"] == 0) {
                $file->delete();
                continue;
            }
            
            $parentPath = $file["file_path"];
            $children   = UserFile::model()->getFilesByPath($parentPath,1);
            foreach ($children as $child) {
                $child->delete();
            }
            $file->delete();
        }
        $this->handleResult(TRUE, 0, "操作成功");
    }
    
    
    private function handleClean() {
        $files = UserFile::model()->findAllByAttributes(array("user_id" => $this->_userId, "is_deleted" => 1));
        $ids = array();
        foreach ($files as $file) {
            array_push($ids, $file["id"]);
        }
        $ids = join(",", $ids);
                if (!empty($ids)) {
            FileStar::model()->deleteAllByFileIds($this->_userId, $ids);
            ShareFile::model()->deleteShareFile($ids);
        }
        $retval = UserFile::model()->deleteAllByAttributes(array("user_id" => $this->_userId, "is_deleted" => 1));
        if ($retval >= 0) {
            $this->handleResult(TRUE, 0, "操作成功");
        }
    }
    
    
    public function handleFileMeta($filePath, $versionId, $userId, $userNick, $action) {
                                $handler = new FileMeta();
        $meta = $handler->getFileMeta($filePath, "version");
        if ($meta) {
            $value = CUtils::getFileVersions($versionId, $action, $userId, $userNick, $meta["meta_value"]);
            $meta["meta_value"] = $value;
        } else {
            $meta = new FileMeta();
            $value = CUtils::getFileVersions($versionId, $action, $userId, $userNick);
            $meta["file_path"]  = $filePath;
            $meta["meta_key"]   = "version";
            $meta["meta_value"] = $value;
        }
        return $meta->save();
    }
    
    public function handleException ($exception)
    {
        $this->result["msg"] = $exception->getMessage();
        echo CJSON::encode($this->result);
        Yii::app()->end();
    }
}
?>